<?php
require_once('TVB/pms/pdes/action/ChapterGetAction.class.php');
require_once('TVB/ImageInfrastructure/Client/requires.php');
require_once('TVB/VideoInfrastructure/Client/requires.php');

class ChapterUpdateAction extends BaseAction 
{
	public $programme_id;
	public $episode_id;
	public $id;
	public $video_id;
	public $new_video_id;
	public $in_time;
	public $out_time;
	public $ii_id;
	public $thumbnail_url;
	public $source_url;
	public $location;
	public $highlighted_cast_roles;
	public $casts;
	public $available_tag_types;
	public $tags;
	public $infos;
	public $status;
	public $created_at;
	public $created_by;
	public $modified_at;
	public $modified_by;

	public $language_id;
	/**
	 * @maxLength 255
	 * @label Chapter Title(chinese)
	 */
	public $title;
	/**
	 * @maxLength 255
	 * @label Chapter Title(english)
	 */
	public $title_en;
	public $description;

	public $deleted_chapters;
	public $attached_info;

	public $role_id;
	public $cast_id;
	public $name_type;
	public $name_last;
	public $name_first;
	public $alphabet;

	public $tag;
	public $new_tag;
	public $from;

	public $ut;
	public $reset;
	public $concurrent_time;
	public function execute(){

		if (!is_null($this->reset))
		{
			$this->setData('vid', $this->video_id);
			$this->setData('act', 'edit');
			$this->setData('type', 'chapter_marking');
			$this->setData('from', $this->from);
			return 'reset';
		}

		Model::$dbo['w']->beginTransaction();
		try{
			if ($this->check_concurrent())
			{
				$this->init_page_data();
				$this->addError('concurrent', array('0105', 'Concurrent update found!'));
				return 'logic-error';
			}

			if(count($this->_errors) > 0){
				$this->init_page_data();
				return 'filter-error';
			}

			//check in/out time
			if ($this->check_chapter())
			{
				$this->init_page_data();
				return 'filter-error';
			}

			//check upload image
			$upload = $this->check_upload_image();
			//output upload error
			if(count($this->_errors) > 0){
				$this->init_page_data();
				return 'filter-error';
			}


			$this->del_chapter();
			$this->add_chapter($upload);
			if (!is_null($this->new_video_id)) $this->move_chapter($this->video_id, $this->new_video_id);

			Model::$dbo['w']->commit();

			if ($this->from == 'programme')
			{
				$this->setData('id', $this->programme_id);
				$this->setData('act', 'edit');
				$this->setData('step', '2#anchor-video');
				return 'programme';
			}
			elseif ($this->from == 'episode')
			{
				$this->setData('id', $this->episode_id);
				$this->setData('act', 'edit');
				$this->setData('step', '2#anchor-video');
				return 'episode';
			}
			elseif ($this->from == 'task')
			{
				return 'task';
			}
			else{
				$this->setData('type', 'video');
				return 'succ';
			}
		}
		catch(Exception $e)
		{
			error_log("Update Video's Chapter Fails: $this->video_id");
			error_log("Request: " . var_export($this, 1));
			error_log("Exception: " . var_export($e, 1));

			Model::$dbo['w']->rollBack();
			return 'system-error';
		}
	}    

	/**
	 * move chapter from one vidoeo to other
	 */
	private function move_chapter($old_video_id, $new_video_id)
	{
		$chapter = new chapter();
		$chapter_list = $chapter->getChapterList($old_video_id);
		foreach($chapter_list as $chapters)
		{
			$new_chapter = new chapter();
			$new_chapter = $new_chapter->get($chapters->id);
			$new_chapter->video_id = $new_video_id;
			$update_id = Model::$dbo['w']->save($new_chapter);
			if ($update_id > 0)
			{
				$this->addInfo("chapter:".AC::LOG_OP_UPDATE.":".$update_id, "move chapter success from {$old_video_id} to {$new_video_id}", json_encode($chapters));
			}
			else
			{
				$this->addError("chapter:".AC::LOG_OP_UPDATE.":".$update_id, "move chapter error from {$old_video_id} to {$new_video_id}", json_encode($chapters));
			}
		}
	}
	/**
	 * add chapter
	 */
	private function add_chapter($upload)
	{
		$len = count($this->id);
		for ($i=0; $i<$len; $i++)
		{
			if (strstr($this->id[$i], "new"))
			{
				$chapter = new chapter();
				$chapter->created_at = date("Y-m-d H:i:s");
				$chapter->created_by = CommonUtils::get_user();
				$chapter->modified_at = $chapter->created_at;
				$chapter->modified_by = $chapter->created_by;
				$chapter->status = AC::STATUS_NEW;
				$chapter->available_tag_types = CommonUtils::get_allow_tags("chapter");
				$chapter->video_id = $this->video_id;
				$chapter->in_time = $this->num_to_sec($this->in_time, $i);
				$chapter->out_time  = $this->num_to_sec($this->out_time, $i);
				$chapter->location = $this->location[$i];
				$chapter->casts = $this->add_cast_field($this->id[$i]);
				$chapter->highlighted_cast_roles = '';
				$chapter->infos = $this->attached_info[$i];
				$chapter->tags = $this->add_tag($this->id[$i],$i);

				if ($upload[$i]['flag'])
				{
					if (is_array($upload[$i]['result']))
					{
						$chapter->ii_id = $upload[$i]['result']['source_id'];
						$chapter->source_url = $upload[$i]['result']['source_url'];
						$chapter->thumbnail_url = $upload[$i]['result']['thumbnail_url'];
					}
				}

				$insert_id = Model::$dbo['w']->save($chapter);
				if($insert_id>0)
				{
					$this->addInfo("chapter:".AC::LOG_OP_CREATE.":".$insert_id, "add chapter success", json_encode($chapter));
				}
				else
				{
					$this->addError("chapter:".AC::LOG_OP_CREATE.":".$insert_id, "add chapter error", json_encode($chapter));
				}

				//update chapter_id to cast of json
				$chapter_2 = new chapter();
				$chapter_j = $chapter_2->get($insert_id);
				$decode = json_decode($chapter_j->casts, true);
				$tmp_arr = array();
				foreach ($decode as $value)
				{
					$tmp_arr[$insert_id] = $value;
				}
				$chapter_j->casts = json_encode($tmp_arr);
				Model::$dbo['w']->save($chapter_j);
				$chapter_id = $insert_id;
			}
			else
			{
				$chapter = new chapter();
				$chapter = $chapter->get($this->id[$i]);
				$chapter->modified_at = date("Y-m-d H:i:s");
				$chapter->modified_by = CommonUtils::get_user();
				$chapter->status = AC::STATUS_NEW;
				$chapter->in_time = $this->num_to_sec($this->in_time, $i);
				$chapter->out_time  = $this->num_to_sec($this->out_time, $i);
				$chapter->location = $this->location[$i];
				$chapter->casts = $this->add_cast_field($this->id[$i]);
				$chapter->infos = $this->attached_info[$i];
				$chapter->tags = $this->add_tag($this->id[$i],$i);

				if ($upload[$i]['flag'])
				{
					if (is_array($upload[$i]['result']))
					{
						$chapter->ii_id = $upload[$i]['result']['source_id'];
						$chapter->source_url = $upload[$i]['result']['source_url'];
						$chapter->thumbnail_url = $upload[$i]['result']['thumbnail_url'];
					}
				}

				$update_id = Model::$dbo['w']->save($chapter);
				if($update_id>0)
				{
					$this->addInfo("chapter:".AC::LOG_OP_UPDATE.":".$this->id[$i], "update chapter success", json_encode($chapter));
				}
				else
				{
					$this->addError("chapter:".AC::LOG_OP_UPDATE.":".$this->id[$i], "update chapter failed", json_encode($chapter));
				}
				$chapter_id = $this->id[$i];
			}

			//handle multiple language
			$this->add_chapter_language($chapter_id,$i);
            $this->add_en_chapter($chapter_id,$i);

            $primary_key = array(
                'id' => $chapter_id
            );
            $fields = array(
                'thumbnail_url', 
                'source_url', 
                'location', 
                'highlighted_cast_roles', 
                'casts', 
                'available_tag_types', 
                'tags', 
                'infos'
            );
            CommonUtils::filterC2A0('chapter', $primary_key, $fields);
            
            $primary_key = array(
                'chapter_id' => $chapter_id
            );
            $fields = array(
                'title', 
                'description'
            );
            CommonUtils::filterC2A0('chapter-language', $primary_key, $fields);
		}
	}


	/**
	 * add ch chapter
	 */
	private function add_chapter_language($chapter_id, $i)
	{
		$chapter_language = new chapter_language();

		if (strstr($this->id[$i], "new"))
		{
			$chapter_language->chapter_id = $chapter_id;
			$chapter_language->language_id = language::getLanguageID(AC::DEFAULT_LANGUAGE);
			$chapter_language->title = trim($this->title[$i]);
			$chapter_language->description = $this->description[$i];
			$new_chapter_id = Model::$dbo['w']->save($chapter_language);
			if ($new_chapter_id >= 0)
			{
				$this->addInfo("chapter-language:".AC::LOG_OP_CREATE.":".$chapter_id, "add chapter language success", json_encode($chapter_language));
			}
			else
			{
				$this->addError("chapter-language:".AC::LOG_OP_CREATE.":".$chapter_id, "add chapter language error", json_encode($chapter_language));
			}
		}
		else
		{
			$chapter_language = $chapter_language->getLangChapterByID($chapter_id,language::getLanguageID(AC::DEFAULT_LANGUAGE));
			$chapter_language->title = trim($this->title[$i]);
			$chapter_language->description = $this->description[$i];
			$update_id = Model::$dbo['w']->save_by_fields($chapter_language, array('chapter_id','language_id'));
			if ($update_id >= 0)
			{
				$this->addInfo("chapter-language:".AC::LOG_OP_UPDATE.":".$chapter_id, "update chapter language success", json_encode($chapter_language));
			}
			else
			{
				$this->addError("chapter-language:".AC::LOG_OP_UPDATE.":".$chapter_id, "update chapter language failed", json_encode($chapter_language));
			}
		}

	}
	/**
	 * add en chapter
	 */
	private function add_en_chapter($chapter_id, $i)
	{
		$chapter_language = new chapter_language();

		if (strstr($this->id[$i],"new"))
		{
			$chapter_language->chapter_id = $chapter_id;
			$chapter_language->language_id = language::getLanguageID(AC::LANGUAGE_EN);
			$chapter_language->title = trim($this->title_en[$i]);
			$chapter_language->description = $this->description[$i];
			$new_chapter_id = Model::$dbo['w']->save($chapter_language);
			if ($new_chapter_id >= 0)
			{
				$this->addInfo("chapter-language:".AC::LOG_OP_CREATE.":".$chapter_id, "add chapter language success", json_encode($chapter_language));
			}
			else
			{
				$this->addError("chapter-language:".AC::LOG_OP_CREATE.":".$chapter_id, "add chapter language error", json_encode($chapter_language));
			}
		}
		else
		{
			$chapter_language = $chapter_language->getLangChapterByID($chapter_id,language::getLanguageID(AC::LANGUAGE_EN));
			if (!$chapter_language) {
				$chapter_language = new chapter_language();
				$chapter_language->chapter_id = $chapter_id;
				$chapter_language->language_id = language::getLanguageID(AC::LANGUAGE_EN);
			}
			
			$chapter_language->title = trim($this->title_en[$i]);
			$chapter_language->description = $this->description[$i];
			$update_id = Model::$dbo['w']->save_by_fields($chapter_language, array('chapter_id','language_id'));
			if ($update_id >= 0)
			{
				$this->addInfo("chapter-language:".AC::LOG_OP_UPDATE.":".$chapter_id, "update chapter language success", json_encode($chapter_language));
			}
			else
			{
				$this->addError("chapter-language:".AC::LOG_OP_UPDATE.":".$chapter_id, "update chapter language failed", json_encode($chapter_language));
			}
		}
	}


	/**
	 * upload image and get image info
	 */
	private function upload_image($tmp_path)
	{
		$result   = CommonUtils::upload_image_to_ii($tmp_path);
		$uploaded = ( array_sum($result['status']) == count($result['status']) );
		if(!$uploaded) return 'upload';
		else return $result;
	}

	/**
	 * number transfer to sec
	 */
	private function num_to_sec($time_type, $i)
	{
		if (!empty($time_type))
		{
			return $time_type[0][$i]*3600+$time_type[1][$i]*60+$time_type[2][$i];
		}
		else
			return '';
	}

	/**
	 * add cast field
	 */
	private function add_cast_field($chapter_id)
	{
		$cast_arr = array();
       	$len = isset($this->role_id[$chapter_id]) ? count($this->role_id[$chapter_id]) : 0;
		for ($i=0; $i<$len; $i++)
		{
			if (empty($this->name_first[$chapter_id][$i])) continue;
		
			$cast_arr[$chapter_id][] = array("cast_id"=>0, "name_type"=>$this->name_type[$chapter_id][$i],"last_name"=>$this->name_last[$chapter_id][$i],"first_name"=>$this->name_first[$chapter_id][$i], "alphabet"=>$this->alphabet[$chapter_id][$i]);
		}

       	return json_encode($cast_arr);
	}

	/**
	 * add tags
	 */
	private function add_tag($chapter_id, $i)
	{
		$tag_arr = array();
		$tag_id  = explode(',',CommonUtils::get_allow_tags('chapter'));

		foreach ($tag_id as $id)
		{
                               
			if (isset($this->tag[$id][$chapter_id]))
			{
				foreach ($this->tag[$id][$chapter_id] as $value)
				{
					if (tag::isRestricted($id))
					{
						$tag_arr[] = $value;
					}
					else
                    {
                        if ( "\t" == $value[0])
                        {
                            $sql = 'SELECT id  FROM tag t where system_label = :label and tag_type_id = :type';
                            $t_id = Model::selectBySql($sql,array(':label'=>urldecode(trim($value)),':type'=>$id));

                            if(empty($t_id))
                            {
                               
                                $tag = new tag();
								$tag->parent_id = 0;
								$tag->tag_type_id = $id;
								$tag->system_label = urldecode(trim($value));
								$ret = Model::$dbo["w"]->save($tag);
							    $tag_arr[] = $ret;
                            }
                            else
                            {
                                $_id = $t_id[0]['id'];
                                if('4' === $id)
                                {
                                    $ret = tag::getLibTag($_id);
                                    $ret = explode(',',$ret);
							        $tag_arr[] = $ret[0];
							        $tag_arr[] = isset($ret[1]) ? $ret[1] : '';
                                }
                                else
                                {
							        $ret = tag::IsParent($_id);
							        $tag_arr[] = $ret;
                                }
                            }
                        }
                        else
                        {
                            
                            $sql = 'SELECT system_label FROM tag t where id = :tid';
                            $data = Model::selectBySql($sql,array(':tid'=>trim($value)));

                            if(empty($data))
                            {
							    $tag_arr[] = $value;
                            }
                            else
                            {
                                if('4' === $id)
                                {
                                    $ret = tag::getLibTag($value);
                                    $ret = explode(',',$ret);
                                    $tag_arr[] = $ret[0];
							        $tag_arr[] = isset($ret[1]) ? $ret[1] : '';
                                }
                                else
                                {
                                    $ret = tag::IsParent($value);
							        $tag_arr[] = $ret;
                                }
                            }
                            
                        }
                      
					}
				}
			}
		}

		$tag = new tag();
		foreach ($tag_id as $new_id)
		{
			if (isset($this->new_tag[$new_id][$chapter_id]))
			{
				foreach ($this->new_tag[$new_id][$chapter_id] as $newtag)
				{
					if (trim($newtag) == '') continue;
					$tag_id = tag::isExist($new_id, urldecode(trim($newtag)));
					if (false != $tag_id) {
                        if('4' === $new_id)
                        {
                            $ret = tag::getLibTag($tag_id);
                             $tag_arr[]= $ret;
                        }
                        else
                        {
                            $ret = tag::IsParent($tag_id);
						    $tag_arr[] = $ret;
                        }
					}
					else
					{
						$tag->parent_id = 0;
						$tag->tag_type_id = $new_id;
						$tag->system_label = urldecode(trim($newtag));
						$ret = Model::$dbo["w"]->save($tag);
						$tag_arr[] = $ret;
					}
					if ($ret >= 0)
					{
						$this->addInfo("tag:".AC::LOG_OP_UPDATE.":".$ret, "update chapter's tag success", json_encode($tag));
					}
					else
					{
						$this->addError("tag:".AC::LOG_OP_UPDATE.":".$ret, "update chapter's tag failed", json_encode($tag));
					}
				}
			}
		}
       	$tag_arr = array_unique($tag_arr);
        $tag_arr = array_filter($tag_arr);
        return implode(",", $tag_arr);
	}

	/**
	 * init tags
	 */
	private function init_tag($chapter_id, $i)
	{
		$tag_arr = array();
		$tag_id  = explode(',',CommonUtils::get_allow_tags('chapter'));

		foreach ($tag_id as $id)
		{
			if (isset($this->tag[$id][$chapter_id]))
			{
				foreach ($this->tag[$id][$chapter_id] as $value)
				{
					$tag = new tag();
					if (tag::isRestricted($id))
					#if ($id != 1)
					{
						$tag_detail = $tag->get($value);
						$tag_arr[$id][] = array(
							'system_label'	=> $tag_detail->system_label, 
							'id'			=> $value
						);
					}
					else
					{
						if ("\t" == $value[0])
						{
							$tag_arr[$id][] = array('system_label'=>urldecode(trim($value)), 'id'=>$value);
						}
						else
						{
							$tag_detail = $tag->get($value);
							$tag_arr[$id][] = array(
								'system_label'	=> urldecode($tag_detail->system_label), 
								'id'			=> $value
							);
                        }
                       
					}
				}
			}

			if (isset($this->new_tag[$id][$chapter_id]))
			{
				foreach ($this->new_tag[$id][$chapter_id] as $newtag)
				{
					$tag_arr[$id][] = array('system_label'=>urldecode($newtag), 'id'=>"\t".$newtag);
				}
			}
		}
       	return $tag_arr;
	}

	/**
	 * del chapter
	 */
	private function del_chapter()
	{
		if (!strstr($this->deleted_chapters,'new') && $this->deleted_chapters)
		{
			$chapter_id = explode(",",$this->deleted_chapters);
			foreach($chapter_id as $id)
			{
				$chapter = new chapter();
				$chapter = $chapter->get($id);
				$chapter->status = AC::STATUS_DELETED;
				$chapter->modified_at = date("Y-m-d H:i:s");
				$chapter->modified_by = CommonUtils::get_user();
				$delete_id = Model::$dbo['w']->save($chapter);
				if ($delete_id > 0)
				{
					$this->addInfo("chapter:".AC::LOG_OP_DELETE.":".$id, "delete chapter success", json_encode($chapter));
				}
				else
				{
					$this->addError("chapter:".AC::LOG_OP_DELETE.":".$id, "delete chapter failed", json_encode($chapter));
				}
			}
		}
	}

	/**
	 * check upload image if valid
	 */
	private function check_upload_image()
	{
		$upload_detail = array();
		$len = count($this->id);
		for($i=0; $i<$len; $i++)
		{
			if (empty($_FILES['screen_capture']['tmp_name'][$i]))
			{
				$upload_detail[$i]['flag'] = false;
				$upload_detail[$i]['result'] = "upload error";
				continue;
			}

			$upload = $this->upload_image($_FILES['screen_capture']['tmp_name'][$i]);
			if (!is_array($upload))
			{
				$upload_detail[$i]['flag'] = false;
				$upload_detail[$i]['result'] = "upload error";
				$this->addError('Video chapter'.($i+1).'.Screen Capture', array('0055',  'Chapter '.($i+1).':Screen Capture'));
			}
			else
			{
				$upload_detail[$i]['flag'] = true;
				$upload_detail[$i]['result'] = $upload;
			}
		}

		return $upload_detail;
	}

	/**
	 * check in_time and out_tim
	 */
	private function check_chapter()
	{
		$len = count($this->id);
		$in_flag  = false;
		$out_flag = false;
		$in_null_flag  = false;
		$out_null_flag = false;
		$cmp_flag    = false;
		$title_flag  = false;
		$tag_flag    = false;
		for($i=0; $i<$len; $i++)
		{
			if ($this->title[$i]=='' && $this->title_en[$i]== '')
			{
				$title_flag = true;
				break;
			}
			if ($this->in_time[0][$i] == '' && $this->in_time[1][$i] == '' && $this->in_time[2][$i] == '')
			{
				$in_null_flag = true;
				break;
			}
			if ($this->out_time[0][$i] == '' && $this->out_time[1][$i] == '' && $this->out_time[2][$i] == '')
			{
				$out_null_flag = true;
				break;
			}

			//length check
			$in_str1 = strlen($this->in_time[0][$i]);
			$in_str2 = strlen($this->in_time[1][$i]);
			$in_str3 = strlen($this->in_time[2][$i]);
			$out_str1 = strlen($this->out_time[0][$i]);
			$out_str2 = strlen($this->out_time[1][$i]);
			$out_str3 = strlen($this->out_time[2][$i]);
			if ($in_str1>8 || $in_str2>4 || $in_str3>4)
			{
				$in_flag = true;
				break;
			}
			if ($out_str1>9 || $out_str2>5 || $out_str3>5)
			{
				$out_flag = true;
				break;
			}

			//compare 
			$start_time =  $this->num_to_sec($this->in_time, $i);
			$end_time   =  $this->num_to_sec($this->out_time, $i);

			if (intval($start_time) > intval($end_time))
			{
				$cmp_flag = true;
				break;
			}
		}

		if ($in_flag)
		{
			$this->addError('in_time', array('0047', 'Chapter '.($i+1).':In Time'));
		}
		if ($out_flag)
		{
			$this->addError('out_time', array('0046', 'Chapter '.($i+1).':Out Time'));
		}
		if ($in_null_flag)
		{
			$this->addError('in_null_time', array('0001', 'Chapter '.($i+1).':In Time'));
		}
		if ($out_null_flag)
		{
			$this->addError('out_null_time', array('0001', 'Chapter '.($i+1).':Out Time'));
		}
		if ($cmp_flag)
		{
			$this->addError('cmp_time', array('0045', 'Chapter '.($i+1)));
		}
		if ($title_flag)
		{
			$this->addError('Video chapter.Chapter Title', array('0035',  'Chapter '.($i+1).':Chapter Title'));
		}

		if ($in_flag || $out_flag || $in_null_flag || $out_null_flag || $cmp_flag || $title_flag) return true;
		else return false;
	}

	/**
	 * check concurrent
	 */
	private function check_concurrent()
	{
		$new_concurrent_time = array();
		$chapter = new chapter();
		$chapter_list = $chapter->getChapterList($this->video_id);
		if (!empty($chapter_list))
		{
			foreach ($chapter_list as $chapter)
			{
				$new_concurrent_time[] = $chapter->modified_at;
			}
		}
		$old_concurrent_time = json_decode($this->concurrent_time, true);
		$cmp_concurrent_time = array_diff_assoc($new_concurrent_time, $old_concurrent_time);
		if (!empty($cmp_concurrent_time))
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	/**
	 * init page data
	 */
	private function init_page_data()
	{
		$action = new ChapterGetAction();
		$action->vid = $this->video_id;
		$action->act = 'edit';
		$action->execute();

		$old_data = $action->getData();
		$new_chapter_ids = array();
		$old_chapter_ids = array();
		$del_chapter_ids = array();
		foreach ($old_data['chapter_list'] as $chapter)
		{
			$new_chapter_ids[] = $chapter->id;
		}

		//retain input content
		$chapter_list = array();
		$init_tag_list = array();
		$len = count($this->id);
		for($i=0; $i<$len; $i++)
		{
			if (strstr($this->id[$i], 'new'))
			{
				$chapter = new chapter();
				$chapter->id = $this->id[$i];
				$chapter->mix_title = $this->title[$i]."\n\t".$this->title_en[$i];
				$chapter->mix_description = $this->description[$i];//.",".$this->description[$i];
				$chapter->created_at = date("Y-m-d H:i:s");
				$chapter->created_by = CommonUtils::get_user();
				$chapter->modified_at = $chapter->created_at;
				$chapter->modified_by = $chapter->created_by;
				$chapter->status = AC::STATUS_NEW;
				$chapter->available_tag_types = CommonUtils::get_allow_tags("chapter");
				$chapter->video_id = $this->video_id;
				if ($this->in_time[0][$i] == '' && $this->in_time[1][$i] == '' && $this->in_time[2][$i] == '')
				{
					$chapter->in_time  = 0;
				}
				else
				{
					$chapter->in_time = $this->num_to_sec($this->in_time, $i);
				}
				if ($this->out_time[0][$i] == '' && $this->out_time[1][$i] == '' && $this->out_time[2][$i] == '')
				{
					$chapter->out_time  = 0;
				}
				else
				{
					$chapter->out_time  = $this->num_to_sec($this->out_time, $i);
				}
				$chapter->location = $this->location[$i];
				$chapter->infos = $this->attached_info[$i];
				$chapter->casts = $this->add_cast_field($this->id[$i]);
				$chapter->highlighted_cast_roles = '';
				$chapter->thumbnail_url = '';
				$chapter->source_url = '';
				$init_tag_list[$this->id[$i]] = $this->init_tag($this->id[$i], $i);
				$chapter_list[] = $chapter;
			}
			else
			{
				$chapter = new chapter();
				$chapter = $chapter->get($this->id[$i]);
				$chapter->modified_at = date("Y-m-d H:i:s");
				$chapter->modified_by = CommonUtils::get_user();
				if ($this->in_time[0][$i] == '' && $this->in_time[1][$i] == '' && $this->in_time[2][$i] == '')
				{
					$chapter->in_time  = 0;
				}
				else
				{
					$chapter->in_time = $this->num_to_sec($this->in_time, $i);
				}

				if ($this->out_time[0][$i] == '' && $this->out_time[1][$i] == '' && $this->out_time[2][$i] == '')
				{
					$chapter->out_time  = 0;
				}
				else
				{
					$chapter->out_time  = $this->num_to_sec($this->out_time, $i);
				}
				$chapter->location = $this->location[$i];
				$chapter->casts = $this->add_cast_field($this->id[$i]);
				$chapter->infos = $this->attached_info[$i];
				$init_tag_list[$this->id[$i]] = $this->init_tag($this->id[$i], $i);
				$chapter->mix_title = $this->title[$i]."\n\t".$this->title_en[$i];
				$chapter->mix_description = $this->description[$i];//.",".$this->description[$i];
				$chapter_list[] = $chapter;
				$old_chapter_ids[] = $this->id[$i];
			}
		}
		$old_data['chapter_list'] = $chapter_list;
		$this->setData('init_tag_list', $init_tag_list);

		//retain new video id
		$old_data['video']['new_video_id'] = $this->new_video_id;
		if (!is_null($this->new_video_id))
		{
			$video = new video();
			$video_detail = $video->getDetails($this->new_video_id);
			$json_param = json_decode($video_detail['video_params']);
			$vi_client = new VideoInfrastructureClient();
			$old['video']['source_url'] = $vi_client->getExportVideoUrlEasily($json_param->export_id);
		}

		foreach ($old_data as $object=>$data)
		{
			$this->setData($object, $data);
		}

		//delete chapter id
		if (empty($old_chapter_ids) && !empty($new_chapter_ids))
		{
			$del_chapter_ids = $new_chapter_ids;
		}
		else
		{
			$del_chapter_ids = array_diff_assoc($new_chapter_ids, $old_chapter_ids);	
		}
		$this->setData('deleted_chapters', implode(",", $del_chapter_ids));

		//jump page
		$this->setData('vid', $this->video_id);
		$this->setData('type', 'chapter_marking');
		$this->setData('act', 'edit');
		$this->setData('from', $this->from);
	}
}
?>
